<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 警告区域 -->
            <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
            <!-- 分类参数区域 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 选择商品分类的级联选择框 -->
                    <el-cascader clearable v-model="selectedCateKeys" :options="cateList"
                                 :props="cascaderProps" @change="handleCascaderChanged"></el-cascader>
                </el-col>
            </el-row>
            <!-- Tab标签页区域 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <el-tab-pane label="动态参数" name="many">
                    <!-- 添加参数按钮 -->
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyTableData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- 循环渲染Tag标签 -->
                                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i"  type="success" closable @close="handleClosed(i,scope.row)">{{item}}</el-tag>
                                <!-- 动态编辑标签 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                                        ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeAttrById(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <!-- 添加属性按钮 -->
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>
                    <!-- 静态属性表格 -->
                    <el-table :data="onlyTableData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- 循环渲染Tag标签 -->
                                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i"  type="success" closable @close="handleClosed(i,scope.row)">{{item}}</el-tag>
                                <!-- 动态编辑标签 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                                          ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeAttrById(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加 动态参数/静态属性 对话框-->
        <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%" @close="addFormClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="110px">
                <el-form-item :label="titleText+'名称'" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addAttr">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改 动态参数/静态属性 对话框-->
        <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%" @close="editFormClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="110px">
                <el-form-item :label="titleText+'名称'" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editAttr">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      // 所有的商品分类数据
      cateList: [],
      // 级联器的配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联器中选中的分类id
      selectedCateKeys: [],
      // Tab中被激活的标签名称
      activeName: 'many',
      // 动态参数
      onlyTableData: [],
      // 静态属性
      manyTableData: [],
      // 添加参数对话框的显示与隐藏
      addDialogVisible: false,
      // 添加参数对话框的表单对象
      addForm: {
        attr_name: ''
      },
      // 添加参数表单的验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在1到10个字符之间', trigger: 'blur' }
        ]
      },
      // 编辑参数对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑参数表单对象
      editForm: {},
      // 编辑参数表单的验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在1到10个字符之间', trigger: 'blur' }
        ]
      },
      // 添加tag 控制按钮/文本框的切换
      inputVisible: false
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败')
      // console.log(res)
      this.cateList = res.data
    },
    // 级联器中选中内容发生变化
    handleCascaderChanged () {
      this.getParamsData()
    },
    // 监听tab标签点击事件
    handleTabClick () {
      // console.log(this.activeName)
      this.getParamsData()
    },
    // 获取动态参数和静态属性列表
    async getParamsData () {
      // 若级联框中选中的不是第三级分类，则清空已保存的数据
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return // his.$message.error('获取参数列表失败')
      // console.log(res.data)
      res.data.forEach(item => {
        // 分割前先判断该数组是否为空，若为空则返回一个空数组，从而解决item.attr_vals为空数组时，分割后为一个空字符串，仍然会渲染出一个tag标签的问题
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 为参数列表中的每一行数据都添加属于自己的用于控制tag的属性，从而解决新增tag时各行联动的问题
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'only') {
        this.onlyTableData = res.data
      } else {
        this.manyTableData = res.data
      }
    },
    // 点击确定，添加参数/属性
    addAttr () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          })
        if (res.meta.status !== 201) return this.$message.error('创建失败')
        this.$message.success('创建成功')
        this.addDialogVisible = false
        await this.getParamsData()
      })
    },
    // 监听 添加属性对话框 关闭事件
    addFormClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 显示编辑参数对话框
    async showEditDialog (attrid) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrid}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数信息失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听 编辑参数窗口关闭 事件，清空表单
    editFormClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确定，修改参数
    editAttr () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.editDialogVisible = false
        this.$message.success('修改成功')
        await this.getParamsData()
      })
    },
    // 删除
    async removeAttrById (attrid) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrid}`)
      if (res.meta.status !== 200) return this.$message.error('删除参数失败')
      this.$message.success('已删除该参数')
      await this.getParamsData()
    },
    // 添加tag 监听文本框失焦事件或键入enter事件
    handleInputConfirm (row) {
      // console.log('ok')
      // 若文本框内的输入数据去除空格之后长度为零，即输入的只有空格，则将输入的数据设置为空字符串
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 若文本框中输入了合法数据，则将新增的tag保存到该行的参数数组中
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 提交数据
      this.saveAttrVals(row)
    },
    // 添加tag 监听按钮的点击事件，显示输入文本框
    showInput (row) {
      row.inputVisible = true
      // 文本框自动获取焦点
      // $nextTick 当页面上的元素被重新渲染之后，执行回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 监听tag标签删除事件
    handleClosed (i, row) {
      // 将该行的参数数组中删除该标签，并向后台保存数据
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    // 项后台提交对参数数组attr_vals的修改，包括新增和删除
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
      if (res.meta.status !== 200) return this.$message.error('修改参数失败')
      this.$message.success('修改参数成功')
    }
  },
  computed: {
    // 如果添加按钮需要被禁用，则返回true，否则返回false
    isBtnDisabled () {
      return this.selectedCateKeys.length !== 3
    },
    // 获取当前选中的第三级分类的id
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 添加参数对话框的标题
    titleText () {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
    .cat_opt {
        margin: 15px 0;
    }
    .el-tag {
        margin: 5px;
    }
    .input-new-tag {
        width: 120px;
    }
</style>
